//
//  PictureSelectorViewController.swift
//  个人微博
//
//  Created by 一介布衣 on 16/3/1.
//  Copyright © 2016年 HUAMANLOU. All rights reserved.
//

import UIKit
import SnapKit
import HMImagePicker

private let pictureSelectCellId = "pictureSelectCell"
private let columnCount: CGFloat = 3
private let maxImageCount = 9

class PictureSelectorViewController: UICollectionViewController {
    
    // 用来保存选择的图片
    lazy var imageList = [UIImage]()
    // 定义数组
    lazy var selectedAssets = [PHAsset]()
    // 构造函数
    init() {
        let flowLayout = UICollectionViewFlowLayout()
        
        // 计算cell的宽度
        let w = (screenWidth - (columnCount+1) * pictureCellMargin)/columnCount
        flowLayout.itemSize = CGSize(width: w, height: w)
        flowLayout.minimumInteritemSpacing = pictureCellMargin
        flowLayout.minimumLineSpacing = pictureCellMargin
        // 设置组间距
        flowLayout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        
        // 必须调用指定的构造函数
        super.init(collectionViewLayout: flowLayout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        // 注册cell
        self.collectionView?.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: pictureSelectCellId)
    }
}


extension PictureSelectorViewController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let detla = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + detla
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureSelectCellId, forIndexPath: indexPath) as! PictureSelectCell
        
        cell.backgroundColor = UIColor.randomColor()
        cell.delegate = self
        
        // 设置cell的图片
        if imageList.count == indexPath.item {
            // 显示多余出来的那一条数据
            cell.image = nil
        }else {
            // 数组内的数据
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
    
}

// 控制器遵守协议，实现协议方法
extension PictureSelectorViewController: PictureSelectCellDelegate {
    // 必选的协议方法，在Swift中如果不实现，就会报错
    func userWillChosePicture() {
        print(__FUNCTION__)
//        // 选择图片使用imagePicker，UIImagePickerController调起系统相册页面
//        let picker = UIImagePickerController()
//        // 如果需要对获取的数据进行操作，需要设置代理并且实现协议方法
//        picker.delegate = self
//        // 如果希望有编辑信息，如需要用到上传用户头像，就需要用到该属性
////        picker.allowsEditing = true
//        presentViewController(picker, animated: true, completion: nil)
        
        // 使用第三方框架
//        HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
//        
//        // 设置图像选择代理
//        picker.pickerDelegate = self;
//        // 设置目标图片尺寸
//        picker.targetSize = CGSizeMake(600, 600);
//        // 设置最大选择照片数量
//        picker.maxPickerCount = 9;
//        
//        [self presentViewController:picker animated:YES completion:nil];
        let picker = HMImagePickerController(selectedAssets: self.selectedAssets)
        // 设置图像选择代理
        picker.pickerDelegate = self
        // 设置目标图片尺寸
        picker.targetSize = CGSizeMake(600, 600)
        // 设置最大选择照片数量
        picker.maxPickerCount = 9
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell: PictureSelectCell) {
        print(__FUNCTION__)
        // 删除图片
        // 在数据源中删除数据
        if let indexPath = collectionView?.indexPathForCell(cell) {
            imageList.removeAtIndex(indexPath.item)
            selectedAssets.removeAtIndex(indexPath.item)
        }
        // 再刷新collectionView
        collectionView?.reloadData()
    }
}

extension PictureSelectorViewController: HMImagePickerControllerDelegate {

    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        // 记录图像，方便在 CollectionView 显示
        imageList = images
        // 记录选中资源集合，方便再次选择照片定位
        if selectedAssets != nil {
            self.selectedAssets = selectedAssets!
        }
        
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - UIImagePickerControllerDelegate
//extension PictureSelectorViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
//    // 实现协议方法，实现了协议方法后，页面的dismiss就交给程序员负责了
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
//        // 添加到图片数组中，数据源发生了变化
//        imageList.append(image)
//        collectionView?.reloadData()
//        
//        //  dismiss页面
//        dismissViewControllerAnimated(true, completion: nil)
//    }
//}

// MARK: - 声明协议
// 只有遵守了NSObjectProtocol 才能够使用weak关键字
protocol PictureSelectCellDelegate: NSObjectProtocol {
    // 声明协议方法
    func userWillChosePicture()
    func userWillDeletePicture(cell: PictureSelectCell)
}

// MARK: - 自定义cell
 class PictureSelectCell: UICollectionViewCell {
    
    // 设置代理属性
    // 注意：声明代理对象，一定要使用weak修饰，防止循环引用
    weak var delegate: PictureSelectCellDelegate?
    
    // 外界设置的图片属性
    var image:UIImage? {
        didSet {
            addBtn.setImage(image, forState: .Normal)
            deleteBtn.hidden = image==nil
        }
    }
    
    // 重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置界面
    private func setupUI() {
        // 添加子视图
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        // 设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        // 添加点击事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
        // 设置按钮的视图显示样式，本身只是按钮的显示样式，但是真正起作用的是按钮内部的imageView在显示图片
        addBtn.imageView?.contentMode = .ScaleAspectFill
        // 设置手动裁减
        addBtn.clipsToBounds = true
    }
    
    // 监听方法：添加
    @objc private func addBtnDidClick() {
        if image != nil {
            print("已经设置了图片了")
            return
        }
        delegate?.userWillChosePicture()
    }
    // 监听方法：删除
    @objc private func deleteBtnDidClick() {
        delegate?.userWillDeletePicture(self)
    }
    
    // 懒加载子视图
    private lazy var addBtn: UIButton = UIButton(backImageName: "compose_pic_add", imageName: nil)
    private lazy var deleteBtn: UIButton = UIButton(backImageName: nil, imageName: "compose_photo_close")
    
    
    
}





